#include "../../Headers/DataAccessors/clientdataaccessor.h"

ClientDataAccessor::ClientDataAccessor(QString databaseName):
    DB(databaseName)
{
}

void ClientDataAccessor::setClient(Client client)
{
    QString values = "insert into client (firstName, lastName, document, phone) values (\""
            + client.getFirstName() + "\", \"" +
            client.getLastName() + "\", \"" +
            client.getDocument() + "\", \"" +
            client.getPhone() + "\")";
    QSqlQuery q(db);
    if (q.exec(values))
        qDebug("all ok");
    else
    {
        qDebug("something wrong");
        qDebug(values.toAscii());
    }
}

Client * ClientDataAccessor::getClient(int id)
{
    QSqlQuery query(db);
    if (query.exec("select id, firstName, lastName, document, phone from client where id = " + QString::number(id)))
    {
        while(query.next())
        {
            Client *client = new Client(
                        query.value(0).toInt(),//id
                        query.value(1).toString(),//firstName
                        query.value(2).toString(),//lastName
                        query.value(3).toString(),//document
                        query.value(4).toString()//phone
                        );
            return client;
        }
    }

    return NULL;
}

QSqlTableModel * ClientDataAccessor::getClients()
{
    QSqlTableModel * model = new QSqlTableModel();
    model->setTable("client");
    model->select();
    return model;
}


bool ClientDataAccessor::deleteClient(Client *client)
{
    QSqlQuery query(db);
    if (query.exec("delete from client where id=" + QString::number(client->getId())))
    {
        return true;
    }
    else
        return false;
}


bool ClientDataAccessor::editClient(Client client)
{
    QSqlQuery query(db);
    if (query.exec("update client set firstName=\"" + client.getFirstName() +
                   "\", lastName=\"" + client.getLastName() +
                   "\", document=\"" + client.getDocument() +
                   "\", phone=\"" + client.getPhone() + "\" where id=" + QString::number(client.getId())))
        return true;
    else
        return false;

}
